#include "Texture2.h"
#include "png.hpp"

namespace p2 {

uint32 Texture2::nextPowerOfTwo(uint32 v)
{
    v--;
    v |= v >> 1;
    v |= v >> 2;
    v |= v >> 4;
    v |= v >> 8;
    v |= v >> 16;
    v++;
    return v;
}

bool Texture2::fromFile(String name)
{
    return fromFile(name, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
}

bool Texture2::fromFile(String name, GLint wrapS, GLint wrapT)
{
	png::image < png::basic_rgba_pixel<GLubyte> > img(name);
	_width = img.get_width();
	_height = img.get_height();
	int fourHeight = _height * 4;
	GLubyte *image_data = new GLubyte[_width * fourHeight];
	int p = 0;
	for ( int j = 0; j < _height; ++j ){
		for ( int i = 0; i < _width; ++i ){
			int x = i;
			int y = _height - j - 1;
			png::basic_rgba_pixel<unsigned char> pix = img.get_pixel(x,y);
			image_data[p] =		pix.red;
			image_data[p + 1] = pix.green;
			image_data[p + 2] = pix.blue;
			image_data[p + 3] = pix.alpha;
			p += 4;
		}
	}
    glGenTextures(1, &_id);
    glBindTexture(GL_TEXTURE_2D, _id);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
    free(image_data);

    GLenum err = glGetError();
    if (err != GL_NO_ERROR) {
        return false;
    }
    return true;
}

}
